<template>
  <div>
    <div class="cropper-wrapper">
      <template>
          <el-upload :class="{ hideShow:hideUploadShow }" ref="upload" :headers="headers" :file-list='fileList' :disabled="disabled" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :limit="limit"
            :on-success="handleSuccess"
            :on-exceed="handleExceed"
            :action="action" 
            :auto-upload="true"
            :before-upload="handleBefore">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-image-viewer  v-if="dialogViewVisible" :on-close="closeViewer" :initial-index="imageIndex" :url-list="urlList" />
      </template>
    </div>
  </div>
</template>

<script>
import { BASEURL } from '../../../public/static/config'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
  name: 'UploadImage',
  props: {
    imageList: {
      type: Array,
      default: () => []
    },
    image: {
      default: '',
      type: String
    },
    disabled: {
      default: false,
      type: Boolean
    },
		limit: {
		  default: 6,
		  type: Number
		},
    size: {
      default: 2,
      type: Number
    },
    type: {
      default: 1,
      type: Number
    },
  },
  components: {
    ElImageViewer
  },
  data() {
    return {
      action: (process.env.BASE_URL || BASEURL) + '/common/oss/single',
      fileList: [],
      dialogImageUrl: '',
      headers: {
        token: this.$store.state.token
      },
      urlList:[],
      imageIndex: 0,
      currentFile: {},
      dialogViewVisible: false,
      imageIndex: 0,
      dialogWidth: '400px',
      hideUploadShow: false,
    }
  },
  computed: {},
  watch: {
    image: {
      immediate: true,
      handler(val) {
        if (val) {
          let item = {url: ''}
          item.url = val
          let array = []
          array.push(item)
          this.fileList = array
          
          if (this.fileList && this.fileList.length > 0 && this.fileList.length >= this.limit) {
            this.hideUploadShow = true
          } else {
            this.hideUploadShow = false
          }
        }
      }
    },
    imageList: {
      immediate: true,
      handler(val) {
        if (val && val.length > 0) {
          let array = []
          for (let index = 0; index < val.length; index++) {
            let element = val[index];
            let item = {}
            item.url = element
            array.push(item)
          }
          this.fileList = array

          if (this.fileList && this.fileList.length > 0 && this.fileList.length >= this.limit) {
            this.hideUploadShow = true
          } else {
            this.hideUploadShow = false
          }
        }
      }
    },
  },
  methods: {
    // 上传按钮 限制图片大小和类型
    handleBefore(file, fileList) {
      this.currentFile = file
      
      if (this.size > 0) {
        const fileSize = file.size / 1024 / 1024 < this.size
        if (!fileSize) {
          this.$message.error('文件大小不能超过' + this.size + 'MB')
          this.removeFile()
          return false
        }
      }
      if (['image/jpeg', 'image/png', 'image/bmp'].indexOf(
        file.type
      ) === -1
      ) {
        this.$message.error('上传图片必须是JPG/PNG/BMP 格式')
        this.removeFile()
        return false
      }

      return true
    },
    handleSuccess(res, file) {
      if (res && res.code === 200) {
        this.urlList.push(res.result)
        this.updateImageList()
      } else {
        this.$message.error(res.message)
      }
    },

    removeFile() {
      if (this.$refs.upload.uploadFiles.length > 0) {
        for (let index = 0; index < this.$refs.upload.uploadFiles.length; index++) {
          const element = this.$refs.upload.uploadFiles[index];
          if (element.uid === this.currentFile.uid) {
            this.$refs.upload.uploadFiles.splice(index, 1)
            break
          }
        }
      }
    },

    handlePictureCardPreview(file) {
      this.handleUrlList()
      for (let index = 0; index < this.urlList.length; index++) {
        const url = this.urlList[index];
        if (file.response && file.response.result &&  file.response.result == url) {
          this.imageIndex = index
          break
        }
      }
      this.dialogViewVisible = true;
    },
    handleExceed(files, fileList) {
      this.$message.error(`当前限制只能选择 ${this.limit} 个文件`);
    },
    handleRemove(file, files) {
      // console.log(111,file, files);
      // console.log(222, this.$refs.upload.uploadFiles);
      this.handleUrlList(files)
      this.updateImageList()
      this.$emit('update:defaultImage', files)
    },
    closeViewer() {
      this.dialogViewVisible = false
    },
    handleUrlList(files) {
      if (this.$refs.upload.uploadFiles.length > 0) {
        let urlList = this.$refs.upload.uploadFiles.map(item => {
          return item.url
        })
        this.$set(this, 'urlList', urlList)
      }
    },
    updateImageList() {
      if (this.$refs.upload.uploadFiles.length > 0) {
        let imageList = this.$refs.upload.uploadFiles.map(item => {
          if (item.status == 'success') {
            return item.response.result
          }
        })
        if (this.limit === 1) {
          if (imageList && imageList.length > 0) {
            this.$emit('update:image', imageList[0])
            this.hideUploadShow = true
          }
        } else {
          if (imageList && imageList.length > 0 && imageList.length >= this.limit) {
            this.hideUploadShow = true
          }
          this.$emit('update:imageList', imageList)
        }
      } else {
        this.$emit('update:image', '')
        this.$emit('update:imageList', [])
        this.hideUploadShow = false
      }
    },
  },
  created() {
    
  },
  mounted() {
    
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
}
</script>

<style lang='scss' scoped>
    ::v-deep .el-upload-list__item {
      transition: none !important;
    }
  .hideShow {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }

  .cropper-wrapper {
    //height: calc(100vh - 50px);
    display: flex;
    justify-content: center;
    align-items: center;
    // transform: translate(-50px, -80px);
    .pre-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        button {
            width: 100px;
            margin-top: 15px;
        }
    }
}

.crop-dialog {
    .cropper-content {
        // padding: 0 40px;
        width: 100%;

        .cropper {
            width: 100%;
            height: 350px;
        }
    }

    .action-box {
        padding: 25px 40px 0 40px;
        display: flex;
        justify-content: center;

        button {
            width: 80px;
            margin-right: 15px;
        }
    }

    .dialog-footer {
        button {
            width: 100px;
        }
    }
}
</style>